


#ifndef __HTTP_IMPL_H__
#define __HTTP_IMPL_H__

#include <string>
#include <vector>

namespace HTTP {

namespace impl{

// Note
// Bad location
// Converts an unsigned hex string to an int
template <typename InputIterator>
int uhex2int(InputIterator begin, InputIterator end)
{
	int n = 0;
	while(begin!=end)
	{
//		n <<= 4;
		char c = *begin;
		if('0'<=c && c<='9')
			n = (n << 4) + c - '0';
		else if('A'<=c && c<='F')
			n = (n << 4) + c - 'A' + 10;
		else if('a'<=c && c<='f')
			n = (n << 4) + c - 'a' + 10;
		else
			break;
		begin++;
		
	}
	return n;
}
// Note
// Is this name right?
// Need test
template <typename InputIterator>
std::string read_chunk(InputIterator begin, InputIterator end)
{
	std::vector<char> buffer;
	buffer.reserve(end - begin);

	const char* rn = "\r\n";
	InputIterator i = std::search(begin, end, rn, rn+2);
	if(i==end)
		return std::string(begin, end);
	int chunk_size = uhex2int(begin, i);
	while(chunk_size > 0)
	{
		i += 2;
		if(chunk_size > end - i)
			chunk_size = end - i;
		begin = i + chunk_size;
		std::copy(i, begin, back_inserter(buffer));
		begin += 2;
		i = std::search(begin, end, rn, rn+2);
		if(i==end)
			break;
		chunk_size = uhex2int(begin, end);
	}

	return std::string(buffer.begin(), buffer.end());
}


}//end namespace HTTP::impl

}//end namespace HTTP


#endif

